<template>
    <div class="header">
        <van-icon name="arrow-left" @click="backTo" />
    </div>
    <div class="edit">
        <div class="opt" style="text-align: left;">
            <van-uploader v-model="fileList" :max-count="1" :after-read="afterRead" />
        </div>
        <div class="opt">
            <van-button @click="saveFn" plain type="success" size="small">保存头像</van-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import request from '@/api/request'
import {useRouter } from 'vue-router'
import { showToast } from 'vant';
const $router = useRouter();
const formData = new FormData();
const afterRead = (data: any) => {
    // 此时可以自行将文件上传至服务器
    // console.log(data);
    formData.append('photo',data.file);
}

let token = localStorage.getItem("AUTOTOKEN")

const fileList = ref<any>([
    {url: localStorage.getItem("USERIMG")}
])

const saveFn = async () => {
    if(token == null) {
        return false;
    }
    let imgUrl;
    await request.photoUpload(formData)
    .then(
        content=>{
            console.log(content)
            let {code , msg , picUrl} = content;
            if(code == 200) {
                imgUrl = picUrl;
            }
            else {
                showToast(msg)
            }
        }
    )

    if(imgUrl) {
        // 设置用户头像的接口
        await request.userImg({token , imgUrl})
        .then(
            content=>{
                let {msg} = content;
                showToast(msg)
            }
        )
    }
}

const backTo = ()=> {
    $router.go(-1)
}

</script>




<style lang="less">
@import '../../static/less/variable.less';
.header {
    height: 50px;
    line-height: 50px;
    padding-left: 10px;
    background-color: #f0f0f0;
    border-bottom: 1px solid #cccccc;
}
.edit {
    padding: @pad;
    margin-top: 20px;
    .opt {
        margin-bottom: 15px;
    }
}
</style>